import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:juju/conf/IMConf.dart';
import 'package:juju/fake/fake_message_tool.dart';
import 'package:juju/model/ConversationDataModel.dart';
import 'package:juju/model/EventQueueModel.dart';
import 'package:juju/model/UserInfoModel.dart';

///======================================
/// 登陆注册归一化
///======================================
void allInOne(String username, String password, BuildContext context) {
  print(">>>>>>>>>>>>>>>>>>> START : 尝试登陆 <<<<<<<<<<<<<<<<<<<\n");
  loginCtl(username, password, context).then((v) {
    if (UserInfoModel.getInstance().login == false) {
      if (UserInfoModel.getInstance().code == "801003") {
        print(
            ">>>>>>>>>>>>>>>>>>> ERROR : 登陆失败 - 用户不存在 - 为新用户注册 <<<<<<<<<<<<<<<<<<<\n");
        registerCtl(username, password).then((value) {
          if (UserInfoModel.getInstance().registerStatus == true) {
            loginCtl(username, password, context);
          } else {
            print(">>>>>>>>>>>>>>>>>>> ERROR : 注册失败 <<<<<<<<<<<<<<<<<<<\n");
          }
        });
      } else if (UserInfoModel.getInstance().code == "801004") {
        print(">>>>>>>>>>>>>>>>>>> 密码错误 <<<<<<<<<<<<<<<<<<<\n");
      } else {
        print(">>>>>>>>>>>>>>>>>>> ERROR : 登陆失败 - 其他原因 <<<<<<<<<<<<<<<<<<<\n");
      }
    } else {
      print(
          "========================= unknow exception =========================");
    }
  });
}

///====================================
/// 获取当前用户信息 / 判断登陆与否
///====================================
Future<void> getCurrentUserInfoCtl(MessageFlutter jmessage) async {
  print("==================== 开始：获取当前用户信息 ======================\n");
  UserInfo? u = await jmessage.getMyInfo();
  if (u == null) {
    print(" ===== 您还未登录账号 ===== \n【获取登录用户信息】null");
    UserInfoModel.getInstance().login = false;
  } else {
    print(" ===== 您已经登录 ===== \n【获取登录用户信息】${u.toJson()}");
    UserInfoModel.getInstance().myInfo = u;
    UserInfoModel.getInstance().login = true;
  }
  print("==================== 完毕：获取当前用户信息 ======================\n");
}

///===================================
/// 添加好友事件监听
///===================================
void addContactNotifyListenerCtl() {
  print("==================== 开始：添加好友事件监听 ======================\n");
  IMConf.getInstance().getJmessage().addContactNotifyListener((event) {
    print("|\n|\n----- Notify from : ${event.fromUserName}");
    print("|\n|\n----- ${event.reason}");
    print("|\n|\n----- ${event.type}");
    if (event.type == JMContactNotifyType.invite_received) {
      // setState(() {
      //存入事件队列
      EventQueueModel.getInstance().jmContactNotifyEvents.add(event);
      // });
    }
  });
  print("==================== 完毕：添加好友事件监听 ======================\n");
}

///==========================================
/// 用户登陆
///==========================================
Future<void> loginCtl(
    String username, String password, BuildContext context) async {
  print("==================== START : loggin ======================\n");
  print("|\n|----- START : 登陆校验");

  if (username == "") {
    print("【登录】username 不能为空");
  }

  if (password == "") {
    print("【登录】password 不能为空");
  }
  print("|\n|----- END : 登陆校验");

  await IMConf.getInstance()
      .getJmessage()
      .login(username: username, password: password)
      .then((onValue) {
    UserInfoModel.getInstance().login = true;
    // setState(() {
    print("======================== 登陆成功 ========================");
    // _loading = false;
    if (onValue is UserInfo) {
      UserInfo u = onValue;
      UserInfoModel.getInstance().myInfo = u;
      print("|\n|----- 【登录后】${u.toJson()}");
      Navigator.of(context).popAndPushNamed("NaviPages");
      UserInfoModel.getInstance().login = true;
    } else {
      print("|\n|----- 【登录后】null}");
      getCurrentUserInfoCtl(IMConf.getInstance().getJmessage());
      Navigator.of(context).popAndPushNamed("NaviPages");
      UserInfoModel.getInstance().login = true;
    }
  }, onError: (error) {
    print("======================== 登陆失败 ========================");
    if (error is PlatformException) {
      PlatformException ex = error;
      print("|\n|----- code = ${ex.code},message = ${ex.message}");
      UserInfoModel.getInstance().code = ex.code;
    } else {
      print("|\n|----- code = ${error.toString()}");
    }
    print("======================== 登陆失败... ========================");
  });
}

///==========================================
/// 用户注册
///==========================================
Future<void> registerCtl(String username, String password) async {
  print("==================== 用户注册 ======================\n");

  await IMConf.getInstance()
      .getJmessage()
      .userRegister(username: username, password: password)
      .then(
    (value) {
      print("|\n|----- =================== 注册成功 =================");
      UserInfoModel.getInstance().registerStatus = true;
    },
    onError: (onError) {
      print("|\n|----- =================== 注册失败 =================");
      print(
          "       |\n       |----- code = ${onError.code},message = ${onError.message}");
    },
  );
}

///========================================
/// 获取会话列表
///========================================
Future<void> getConversationListCtl() async {
  print("======================= getConversationList =====================");
  List<ConversationInfo> conversations =
      await IMConf.getInstance().getJmessage().getConversations();
  int index = 0;
  for (ConversationInfo info in conversations) {
    print('|\n|\n----- 会话$index：${info.title}');
  }
  // dataList = conversations;
  // setState(() {
  // _loading = false;
  // TODO: 传值调用与传引用调用，可能导致会话列表不刷新
  ConversationDataModel.getInstance().conversationList = conversations;
  // });
}

///=================================================
/// 更新用户信息
///=================================================

Future<void> updateMyInfoCtl(
    {int? birthday,
    String? nickname,
    String? signature,
    String? region,
    String? address,
    Gender? gender,
    Map<dynamic, dynamic>? extras}) async {
  await IMConf.getInstance()
      .getJmessage()
      .updateMyInfo(
          birthday: birthday,
          nickname: nickname,
          signature: signature,
          region: region,
          address: address,
          gender: gender,
          extras: extras)
      .then((value) {
    print("===================== 更新成功 =====================\n");
  }, onError: (e) {
    if (e is PlatformException) {
      PlatformException ex = e;
      print("======================== 更新失败 =========================");
      print("|\n| ----- code: ${ex.code}");
      print("|\n| ----- details: ${ex.details}");
      print("|\n| ----- message: ${ex.message}");
      print("\n");
    }
  });
}
